package com.lagou.rpc.consumer.zk;

import com.lagou.rpc.consumer.client.RpcClient;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 50705 2021/11/19
 **/
@Component
public class ConnZKServer {

    // 服务器列表,格式: ip_port
    public static List<String> serverInfoList;

    public static List<RpcClient> rpcClientList = new ArrayList<>();

    public static Map<String, RpcClient> SERVER_MAP = new HashMap<>();


    /**
     * 获取服务器列表
     */
    public static List<String> getServerInfo(){
        ZkClient zkClient = ZKClientUtil.getInstance();
        serverInfoList = zkClient.getChildren(ZKClientUtil.pathPre);
        System.out.println("此时zk上服务节点: " + serverInfoList.toString());
        return serverInfoList;
    }

    public ConnZKServer(){
        // 与每一个服务创建rpc连接
        connRpcClient();

        ZkClient zkClient = ZKClientUtil.getInstance();
        // 注册节点变更监听
        zkClient.subscribeChildChanges(ZKClientUtil.pathPre, new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
                // 子节点
                System.out.println(">>>parentPath: " + parentPath + "  currentChilds: " + currentChilds);
                // 关闭所有rpc
                for(RpcClient client : rpcClientList){
                    client.close();
                }
                // 连接现有服务
                connRpcClient();
            }
        });

        //注册节点数据监听
        zkClient.subscribeDataChanges(ZKClientUtil.pathPre, new IZkDataListener() {
            public void handleDataChange(String path, Object data) throws Exception {
                System.out.println(path+"该节点内容被更新，更新后的内容"+data);
            }
            public void handleDataDeleted(String s) throws Exception {
                System.out.println(s+" 该节点被删除");
            }
        });

    }

    public static void connRpcClient(){
        rpcClientList = new ArrayList<>();
        SERVER_MAP = new HashMap<>();
        // 与zk上的每一个服务建立连接
        for(String info : getServerInfo()){
            String[] s = info.split("_");
            RpcClient client = new RpcClient(s[0], Integer.valueOf(s[1]));

            rpcClientList.add(client);
            SERVER_MAP.put(info, client);
        }
    }




}
